package com.zr.corporate.service.impl;

import com.zr.corporate.mapper.CorporateFactoryMapper;
import com.zr.corporate.pojo.*;
import com.zr.corporate.service.CorporateFactoryService;
import com.zr.planclass.meiju.StatusEnum;
import com.zr.util.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2019/9/24.
 */
@Service
public class CorporateFactoryServiceImpl implements CorporateFactoryService {
    @Autowired
    private CorporateFactoryMapper corporateFactoryMapper;

    @Override
    public ResultVo queryPage(CorporateFactorySelectVo corporateFactorySelectVo) {
        //根据条件查询数量
        int count = corporateFactoryMapper.queryCount(corporateFactorySelectVo);
        //根据条件查询数据
        List<FactoryVo> factoryVos = corporateFactoryMapper.queryData(corporateFactorySelectVo);
        //把数据包装进allRecords
        AllRecords allRecords = new AllRecords();
        allRecords.setPageIndex(corporateFactorySelectVo.getPageIndex());
        allRecords.setPageSize(corporateFactorySelectVo.getPageSize());
        allRecords.resetTotalPage(count);
        allRecords.setTotalNumber(count);
        allRecords.setDataList(factoryVos);

        return ResultVoBuilder.success(allRecords);
    }

    @Override
    @Transactional
    public ResultVo add(@Valid List<CorporateFactoryAddVo> corporateFactoryAddVoList) {
        //验证数据
        ResultVo assigement = assigement(corporateFactoryAddVoList);
        if (!assigement.getSuccess()) {
            return assigement;
        }
        //把左边对象中的参数值自动赋值给右边对象中的参数值
        //注意必须是相同类型和相同参数名的才能copy
        List<FactoryVo> newFactory = fuzhi(corporateFactoryAddVoList);
        corporateFactoryMapper.addList(newFactory);
        return ResultVoBuilder.success();
    }

    public List<FactoryVo> fuzhi(List<CorporateFactoryAddVo> corporateFactoryAddVoList){
        List<FactoryVo> newFactoryAddVo = new ArrayList<>();
        Date nowDate = new Date();
        for (CorporateFactoryAddVo corporateFactoryAddVo:corporateFactoryAddVoList){
            //给创建人和创建时间等参数赋值
            FactoryVo factoryVo = new FactoryVo();
            BeanUtils.copyProperties(corporateFactoryAddVo,factoryVo);
            factoryVo.setCreateName("小明");
            factoryVo.setCreateTime(nowDate);
            factoryVo.setUpdateName("小明");
            factoryVo.setUpdateTime(nowDate);
            newFactoryAddVo.add(factoryVo);
        }
        return newFactoryAddVo;
    }

    @Override
    @Transactional
    public ResultVo update(@Valid CorporateFactoryUpdateVo corporateFactoryUpdateVo) {
        //验证要修改的数据是否存在
        List<FactoryVo> factoryVoList = corporateFactoryMapper.queryBylegalPlantCode(corporateFactoryUpdateVo.getLegalPlantCode());
        if (CollectionUtils.isEmpty(factoryVoList)) {
            return ResultVoBuilder.error("500", "修改的数据不存在！");
        }
        //验证是否是禁用状态的数据
        Integer enabled = factoryVoList.get(0).getEnabled();
        if (enabled == StatusEnum.QIYONG.getStatusValue()) {
            return ResultVoBuilder.error("500", "启用状态的数据不能修改！");
        }
        //给修改人员和修改时间赋值
        FactoryVo factoryVo = new FactoryVo();
        BeanUtils.copyProperties(corporateFactoryUpdateVo, factoryVo);
        factoryVo.setUpdateName("小明");
        factoryVo.setUpdateTime(new Date());

        //修改语句。
        corporateFactoryMapper.update(factoryVo);
        return ResultVoBuilder.success();
    }


    @Override
    public ResultVo updateStatus(@Valid CorporateFactoryUpdateStatusVo corporateFactoryUpdateStatusVo) {
        //验证要修改的数据是否存在
        FactoryVo factoryVo = corporateFactoryMapper.queryById(corporateFactoryUpdateStatusVo.getId());
        if (factoryVo == null) {
            return ResultVoBuilder.error("500", "修改的数据不存在！");
        }
        //给修改人员和修改时间赋值
        FactoryVo factoryVo1 = new FactoryVo();
        BeanUtils.copyProperties(corporateFactoryUpdateStatusVo, factoryVo1);
        factoryVo1.setUpdateName("小明");
        factoryVo1.setUpdateTime(new Date());
        corporateFactoryMapper.updateStatus(factoryVo1);
        return ResultVoBuilder.success();
    }


    @Override
    public ResultVo queryCorporateByUserId(Integer userId) {
        if (userId == null) {
            //如果session中没有拿到信息就让用户重新登录
        }
        List<CorporateVo> legalPersonVos = corporateFactoryMapper.queryCorporateByUserId(userId);
        return ResultVoBuilder.success(legalPersonVos);
    }

    @Override
    public ResultVo importFile(MultipartFile file) throws Exception {
       /* 1.给用户提供导入模板*/
        //2.提示版本问题，询问产品经理支持哪种版本的导入格式，2007版本的导入模板，根据版本不同，poi导入技术的读取方式不同
        String fileName = file.getOriginalFilename();
        if (!fileName.contains("xlsx")) {
            return ResultVoBuilder.error("只能导入2007版本，以xlsx结尾的Excel文件");
        }
        //3.模板是否是需要导入的模板，验证模板是否正确  4.格式问题，必须保持统一格式，统一为字符串格式导入
        ResultVo<List<CorporateFactoryAddVo>> resultVo = validateFile(file);
        if (!resultVo.getSuccess()) {
            return resultVo;
        }
       /*
        5.验证不为空字段是否为空
        6.验证字符长度是否符合需求*/
        ResultVo<List<CorporateFactoryAddVo>> yanzheng = yanzheng(resultVo.getData());
        if (!yanzheng.getSuccess()) {
            return yanzheng;
        }
        //验证重复
        ResultVo<List> chongfu = chongfu(yanzheng.getData());
        if (!chongfu.getSuccess()) {
            return chongfu;
        }
        //7.验证数据是否存在也就是是否合法
        //入库
        ResultVo add = add(yanzheng.getData());
        if (!add.getSuccess()) {
            return add;
        }
        return null;
    }

    public ResultVo chongfu(List<CorporateFactoryAddVo> corporateFactoryAddVoList) {
        List<String> personCodeList = new ArrayList<>();
        List<String> plantCodeList = new ArrayList<>();
        for (CorporateFactoryAddVo corporateFactoryAddVo : corporateFactoryAddVoList) {
            personCodeList.add(corporateFactoryAddVo.getLegalPersonCode());
            plantCodeList.add(corporateFactoryAddVo.getLegalPlantCode());
        }
        List<String> newCodeList = new ArrayList<>();
        List<String> repeatCodeList = new ArrayList<>();
        for (String code : personCodeList) {
            if (newCodeList.contains(code)) {
                repeatCodeList.add(code);
            } else {
                newCodeList.add(code);
            }
        }
        if (!repeatCodeList.isEmpty()) {
            return ResultVoBuilder.error("没有要添加的法人编码，错误法人编码为:" + repeatCodeList.toString());
        }
        return ResultVoBuilder.success();

    }

    public ResultVo yanzheng(List<CorporateFactoryAddVo> corporateFactoryAddVoList) {
          /*
        5.验证不为空字段是否为空
        6.验证字符长度是否符合需求
        7.验证数据是否存在也就是是否合法
        8.验证数据是否重复
        9.对于需要转换的数据进行数据转换，比如数据库存的数据为数字格式，用户输入的为汉字，需要把汉字转换为数字存储*/


        for (CorporateFactoryAddVo corporateFactoryAddVo : corporateFactoryAddVoList) {
            if (StringUtils.isEmpty(corporateFactoryAddVo.getLegalPlantCode())) {
                return ResultVoBuilder.error("工厂编码不能为空！");
            } else {
                if (corporateFactoryAddVo.getLegalPlantCode().length() > 100) {
                    return ResultVoBuilder.error("工厂编码长度不能大于100字符！");
                }
            }
            //验证是否为合法汉字，如果合法，给状态值进行转换进行赋值。
            if (StatusEnum.getValue(corporateFactoryAddVo.getEnabledName()) == null) {
                return ResultVoBuilder.error("状态只能是启用和禁用！");
            } else {
                corporateFactoryAddVo.setEnabled(StatusEnum.getValue(corporateFactoryAddVo.getEnabledName()));
            }
//              }

        }
        return ResultVoBuilder.success(corporateFactoryAddVoList);

    }

    public ResultVo<List<CorporateFactoryAddVo>>    validateFile(MultipartFile file) throws Exception {
//        模板是否是需要导入的模板，验证模板是否正确
        //poi核心类，用来读取excel表格中的数据
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        //获取单元格中的信息 at0是获取sheet1中的数据。
        XSSFSheet sheet = workbook.getSheetAt(0);
        System.out.println(sheet.getRow(sheet.getFirstRowNum()).getCell(0));
        //验证第一列第一行的表格标头信息是否为 “询价单导入”，如果不是，提示模板错误。
        if (!String.valueOf(sheet.getRow(sheet.getFirstRowNum()).getCell(0)).equals("法人工厂导入模板")) {
            return ResultVoBuilder.error("模板错误，请检查模板！", "500");
        }
        List<CorporateFactoryAddVo> inquirySpareDetailVoList = new ArrayList<>();
        //遍历excel表格中的所有数据，从第五行开始读取，没有数据时终止遍历。
        for (int i = sheet.getFirstRowNum() + 3; i <= sheet.getLastRowNum(); i++) {
            //读取每一行的数据
            XSSFRow xssfRow = sheet.getRow(i);
            if (xssfRow != null) {
                if (!String.valueOf(xssfRow.getCell(0)).equals("")
                        || !String.valueOf(xssfRow.getCell(1)).equals("")
                        || !String.valueOf(xssfRow.getCell(2)).equals("")
                        || !String.valueOf(xssfRow.getCell(3)).equals("")
                        ) {
                    //把每一行的数据放入到实体类中
                    CorporateFactoryAddVo inquiryImportVo = build(xssfRow);
                    //把实体类中的数据放入到list集合中
                    inquirySpareDetailVoList.add(inquiryImportVo);
                }

            }
        }
        return ResultVoBuilder.success(inquirySpareDetailVoList);
    }

    public CorporateFactoryAddVo build(XSSFRow xssfRow) {
        CorporateFactoryAddVo corporateFactoryAddVo = new CorporateFactoryAddVo();
//        try {
        corporateFactoryAddVo.setLegalPersonCode(String.valueOf(xssfRow.getCell(0)));
      /*  }catch (Exception e){
            return ResultVoBuilder.error("编码格式只能为文本格式，请检查格式！");
        }*/
        corporateFactoryAddVo.setLegalPlantCode(String.valueOf(xssfRow.getCell(1)));
        corporateFactoryAddVo.setLegalPlantDec(String.valueOf(xssfRow.getCell(2)));
        corporateFactoryAddVo.setEnabledName(String.valueOf(xssfRow.getCell(3)));
        return corporateFactoryAddVo;
    }

    public ResultVo assigement(List<CorporateFactoryAddVo> corporateFactoryAddVoList) {
        List<String> personCodeList = new ArrayList<>();
        List<String> plantCodeList = new ArrayList<>();
        for (CorporateFactoryAddVo corporateFactoryAddVo : corporateFactoryAddVoList) {
            personCodeList.add(corporateFactoryAddVo.getLegalPersonCode());
            plantCodeList.add(corporateFactoryAddVo.getLegalPlantCode());
        }

//        //验证数据库中是否存在法人编码
//        List<String> personCodes = corporateFactoryMapper.queryByPersonCodes(personCodeList);
////        codeList.removeAll(planClassCodes);
//        if (!personCodes.isEmpty()) {
//            return ResultVoBuilder.error("存在的法人编码为:" + personCodes);
//        }

        //验证数据库中是否存在工厂编码
        List<String> plantCodes = corporateFactoryMapper.queryByPlantCodes(plantCodeList);
//        nameList.removeAll(planClassNames);
        if (!plantCodes.isEmpty()) {
            return ResultVoBuilder.error("存在的工厂编码为:" + plantCodes);
        }

        return ResultVoBuilder.success();
    }

    @Override
    public ResultVo exportExcel(HttpServletResponse response, CorporateFactorySelectVo corporateFactorySelectVo)throws Exception {
        //1.定义一个导出模板
        //2.从数据库中查询出将要导出的数据
        //根据条件查询数量
        int count =  corporateFactoryMapper.queryCount(corporateFactorySelectVo);
        if (count>10000){
            return ResultVoBuilder.error("导出数据不能大于10000条，请选择条件在进行导出！");
        }
        //根据条件查询数据
        List<FactoryVo> factoryVoList = corporateFactoryMapper.queryDataExport(corporateFactorySelectVo);
        //对需要转化的数据进行转化
        for (FactoryVo factoryVo:factoryVoList){
            factoryVo.setEnabledName(StatusEnum.getName(factoryVo.getEnabled()));
        }
        //把从数据库中查询出的数据赋值给导出模板
        //获取响应输出流
        ServletOutputStream out = response.getOutputStream();
        //给输出文件设置名称
        POIClass.toPackageOs(response, "法人工厂导出");
        //读取模板中的数据
        InputStream in = ExportUtil.toPackageIn("templates/法人工厂导出模板.xlsx");

        //根据模板的数据、把查询出来的数据给摸版SHeet1组中的数据赋值、把excel输出到浏览器上
        writeDataToExcel(in, "Sheet1", factoryVoList, out);
        if (in != null) {
            in.close();
            out.close();
        }
        return null;
    }

    // 由于此方法不能通用, 所以单独写在这里
    private void writeDataToExcel(InputStream in, String sheetName,List<FactoryVo> factoryVoList, ServletOutputStream out) throws Exception {
        //POi读取模板
        XSSFWorkbook wb = new XSSFWorkbook(in);
        //读取sheet1中的数据
        Sheet sheet = wb.getSheet(sheetName);
        if (sheet != null) {
            //向sheet1中赋值，设置样式
            toResultListValueInfo(sheet, factoryVoList);
        }
        //把数据写入到输出流中
        wb.write(out);
        //关闭poi方法
        wb.close();
    }


    /**
     * 插入excel表中项目信息
     *
     * @param sheet
     */
    private void toResultListValueInfo(Sheet sheet, List<FactoryVo> factoryVoList) {
        //从第4行开始赋值
        int row_column = 3;
        //遍历数据集合
        for (FactoryVo obj : factoryVoList) {
            //创建一行的方法
            Row row = sheet.createRow(row_column);
            // 给第一列法人编码赋值
            POIClass.toCellValue(row,0, obj.getLegalPersonCode() + "");
            // 给第二列工厂编码赋值
            POIClass.toCellValue(row, 1, obj.getLegalPlantCode() + "");
            // 给第三列工厂描述赋值
            POIClass.toCellValue(row, 2, obj.getLegalPlantDec() + "");
            // 给状态赋值
            POIClass.toCellValue(row, 3, obj.getEnabledName() + "");
        /*    //给描述赋值
            POIClass.toCellValue(row, 4, obj.getRemark() + "");*/
            row_column++;
        }
    }
}
